<template>
  <div style="height: 100%">
    <!-- {{ currentChoose }} -->
    <div
      v-for="(item, index) in currentChoose"
      :key="index"
      class="flex justify-center items-center"
      :class="index ? 'mt-2' : ''"
    >
      <el-time-picker
        v-bind="_options"
        v-model="currentChoose[index]"
        :disabled="_options.disabled"
        @change="handleChange"
        style="margin-top: 2px"
      />
      <div class="flex ml-2 w-2" v-if="!_options.disabled">
        <ElButton type="primary" link size="small" v-if="!index" @click="plusTime(index)"
          >新增</ElButton
        >
        <ElButton type="danger" link size="small" v-if="index" @click="minusTime(index)"
          >删除</ElButton
        >
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { ElTimePicker } from 'element-plus'

export type ITimeRange = {
  startTime: string
  endTime: string
}

type IOptions = Omit<InstanceType<typeof ElTimePicker>['$props'], 'modelValue'>
const props = defineProps<{
  modelValue: ITimeRange[] | string
  options?: IOptions
}>()

// 合并默认配置和传入的自定义配置
const _options = computed<IOptions>(() => {
  const defaultOptions: IOptions = {
    valueFormat: 'HH:mm:ss',
    format: 'HH:mm:ss',
    isRange: true,
  }
  return { ...defaultOptions, ...props }
})

// 当前选择的时间范围
const currentChoose = ref<string[][]>([])

// 初始化数据
const initializeData = () => {
  if (!props.modelValue || !Array.isArray(props.modelValue)) {
    currentChoose.value = [['', '']]
    return
  }

  currentChoose.value = props.modelValue.map((item) => [item.startTime, item.endTime])
}

// 处理时间范围变化
const handleChange = () => {
  handleDataEmits()
}

// 添加时间范围
const plusTime = (index: number) => {
  currentChoose.value.splice(index + 1, 0, ['', ''])
  handleDataEmits()
}

// 删除时间范围
const minusTime = (index: number) => {
  if (index === 0) return
  currentChoose.value.splice(index, 1)
  handleDataEmits()
}

const emits = defineEmits(['update:modelValue'])
// 统一处理数据回显
const handleDataEmits = () => {
  const filteredData = currentChoose.value.filter((item) => item && item.length === 2)
  if (!filteredData.length) {
    emits('update:modelValue', [{ startTime: '', endTime: '' }])
    return
  }

  const formattedData = filteredData.map((item) => ({
    startTime: item[0] || '',
    endTime: item[1] || '',
  }))
  emits('update:modelValue', formattedData)
}

// 监听父组件传递的 modelValue 变化
watch(
  () => props.modelValue,
  () => {
    initializeData()
  },
  { immediate: true },
)

// 初始化数据
initializeData()
</script>

<style scoped>
.flex {
  display: flex;
}
.justify-center {
  justify-content: center;
}
.items-center {
  align-items: center;
}
.mt-2 {
  margin-top: 8px;
}
.mr-2 {
  margin-right: 6px;
  margin-left: 2px;
}
.ml-2 {
  margin-left: 2px;
}
.w-2 {
  width: 2rem;
}
</style>
